Mastering Python: a Comprehensive Guide by Américo Moreira

Mastering Python: a Comprehensive Guide by Américo Moreira

Author:Américo Moreira
Language: eng
Format: epub
Publisher: Ocirema
Published: 2023-09-29T00:00:00+00:00


Chapter 7 - File Handling and Input/Output

7.1 Reading and Writing Files

In Python, file handling is an essential skill that allows you to work with different types of files, such as text files, CSV files, JSON files, and more. In this section, we will explore how to read and write files using Python.

Opening and Closing Files

Before we can read or write to a file, we need to open it. Python provides a built-in function called open() that allows us to open a file in different modes, such as read mode ('r'), write mode ('w'), append mode ('a'), and more. Here’s the basic syntax for opening a file:

file = open('filename', 'mode')

In the above syntax, 'filename' represents the name of the file you want to open, and 'mode' represents the mode in which you want to open the file.

Once we are done working with a file, it is important to close it to free up system resources. We can use the close() method to close the file. Here’s an example:

file = open('filename', 'mode')

# Perform file operations

file.close()

Reading Files

To read the contents of a file, we can use the read() method. This method reads the entire contents of the file as a string. Here’s an example:

file = open('filename', 'r')

content = file.read()

print(content)

file.close()

In the above example, we open the file in read mode ('r'), read its contents using the read() method, and then print the content. Finally, we close the file using the close() method.

If you want to read only a certain number of characters from a file, you can pass the number of characters as an argument to the read() method. For example, to read the first 100 characters of a file, you can use the following code:

file = open('filename', 'r')

content = file.read(100)

print(content)

file.close()

Writing Files

To write to a file, we need to open it in write mode ('w'). If the file does not exist, Python will create it. If the file already exists, opening it in write mode will overwrite its contents. Here’s an example:

file = open('filename', 'w')

file.write('Hello, World!')

file.close()

In the above example, we open the file in write mode ('w'), write the string 'Hello, World!' to the file using the write() method, and then close the file.

If you want to append content to an existing file instead of overwriting it, you can open the file in append mode ('a'). Here’s an example:

file = open('filename', 'a')

file.write('This is additional content.')

file.close()

In the above example, we open the file in append mode ('a'), write the string 'This is additional content.' to the file, and then close the file.

Error Handling

When working with files, it is important to handle potential errors that may occur. One common error is when the file you are trying to open does not exist. To handle such errors, you can use a try-except block. Here’s an example:

try:

file = open('filename', 'r')

content = file.read()

print(content)

file.close()

except FileNotFoundError:

print('File not found.')

In the above example, we try to open the file and read its contents. If the file does not exist, a FileNotFoundError will be raised, and the code inside the except block will be executed.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.